﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Reflection;

namespace Odyssey.Behaviors
{
    public class InvokeCommandAction : TriggerAction<FrameworkElement>
    {

        protected override void Invoke(object parameter)
        {
            ICommand command = GetCommand();
            object param = CommandParameter ?? this.AssociatedObject.DataContext;
            if ((command != null) && command.CanExecute(param))
            {
                command.Execute(param);
            }
        }

        private ICommand GetCommand()
        {
            if (string.IsNullOrEmpty(CommandName)) return null;
            var viewModel = AssociatedObject.DataContext;
            if (viewModel == null) return null;


            PropertyInfo pi = viewModel.GetType().GetProperty(CommandName);
            if (pi == null) return null;
            return pi.GetValue(viewModel, null) as ICommand;
        }

        public string CommandName { get; set; }



        public object CommandParameter
        {
            get { return (object)GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter", typeof(object), typeof(InvokeCommandAction), new PropertyMetadata(null));

        

    }
}
